<template>
  <div class="page">
    <!-- 图片区域 -->
    <div class="preview">
      <img
        :src="imageUrl"
        alt=""
        class="preview-image"
        v-if="taskDetail.status === TaskType.SUCCESS && !isSubmitting" />
      <div class="error" v-if="taskDetail.status === TaskType.FAIL && !isSubmitting">
        <img src="@/assets/photoframe/error.png" alt="" class="error-image" />
        <p>Generation failed</p>
      </div>
      <div class="loading-place" v-if="isSubmitting">
        <ProgressNumber class="progress-display" :auto-start="true" />
        <Vue3Lottie :animationData="loadingJson" height="506" width="336" />
        <ShinyText text="​​Generating ...​" :disabled="false" :speed="3" class-name="shiny-text" />
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-buttons">
      <button class="btn btn-primary" :disabled="!imageUrl_req" @click="buyNow">Buy Now</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { QShopAPI } from '@/api/qshop';
  import router from '@/router/route';
  import { computed, onMounted, onUnmounted, ref } from 'vue';
  import ShinyText from '@/components/basic/ShinyText.vue';
  import { Vue3Lottie } from 'vue3-lottie';
  import loadingJson from '@/assets/lottie/loading_bg.json';
  import { TaskType } from '@/types/ai';
  import { showToast } from 'vant';
  import { useOrderStore } from '@/store/order';
  import { OrderType } from '@/api/nex';
  import ProgressNumber from '@/views/activity/components/ProgressNumber.vue';

  const taskId = ref((router.currentRoute.value.query.task_id as string) || '');
  const taskDetail = ref<any>({});
  const orderStore = useOrderStore();

  // 图片URL
  const imageUrl_req = computed(() => taskDetail.value?.img || ''); //传参图片
  
  const imageUrl = computed(() => taskDetail.value?.result_imgs?.[0].img_url || '');


  // 提交状态和任务状态
  const isSubmitting = ref(false);
  // 保存轮询的timer ID
  const pollTimer = ref<number | null>(null);

  const buyNow = () => {
    const params = {
      product_id: taskDetail.value.gen_template.product_id,
      pay_method: 1,
      order_type: OrderType.POD,
      quality: 1,
      img_url: imageUrl_req.value,
    };
    orderStore.createOrderHandle(params);
  };

  // 返回
  const goBack = () => {
    router.back();
  };

  // 查询任务状态
  const checkTaskStatus = async () => {
    if (!taskId.value) return;

    const params = {
      task_id: taskId.value,
    };
    const res = await QShopAPI.generateTaskDetail(params);
    taskDetail.value = res.data;
    if (res.data.status === TaskType.PROCESSING) {
      // 任务开始，继续查询
      // 先清除之前可能存在的timer，防止多个timer同时运行
      if (pollTimer.value) {
        clearTimeout(pollTimer.value);
      }
      pollTimer.value = window.setTimeout(() => {
        checkTaskStatus();
      }, 3000);
      isSubmitting.value = true;
    } else {
      isSubmitting.value = false;
      // 任务完成后清除timer
      if (pollTimer.value) {
        clearTimeout(pollTimer.value);
        pollTimer.value = null;
      }
    }
  };

  onMounted(() => {
    if (taskId.value) {
      checkTaskStatus();
    }
  });

  // 组件卸载时清除轮询
  onUnmounted(() => {
    if (pollTimer.value) {
      clearTimeout(pollTimer.value);
      pollTimer.value = null;
    }
  });
</script>

<style scoped lang="scss">
  // 基础样式
  .page {
    height: 100vh;
    height: 100dvh;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    padding-top: 56px;
    padding-bottom: env(safe-area-inset-bottom, 0);
  }
  .head {
    padding: 8px 16px 0 16px;
  }
  .preview {
    flex: 1;
    // background-color: #f8f8f8;
    display: flex;
    justify-content: center;
    align-items: center;
    // padding: 0 16px;
    position: relative;
    img {
      width: 100%;
    }

    .error {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      img {
        width: 64px;
        margin-bottom: 16px;
      }
      p {
        font-size: 16px;
        font-weight: 400;
        color: #7a7a7a;
      }
    }

    .loading-place {
      position: absolute;
      // border-radius: 8px;
      overflow: hidden;
      width: 100%;
      height: 100%;
      bottom: 0;
      left: 0;
      right: 0;
      .shiny-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #7a7a7a;
        white-space: nowrap;
        font-size: 18px;
        font-weight: 400;
        height: 20px;
        line-height: 20px;
      }
      .progress-display {
        position: absolute;
        top: 16px;
        left: 16px;
      }
    }
  }

  .bottom-buttons {
    display: flex;
    gap: 16px;
    padding: 16px 16px;
    .btn-primary {
      flex: 1;
      height: 40px;
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      background: #f76b1b;
      padding: 0px 20px;
      &:disabled {
        opacity: 0.5;
        pointer-events: none;
      }
      &:active:not(:disabled) {
        opacity: 0.9;
      }
    }
    .btn-secondary {
      height: 40px;
      color: #f76b1b;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      background: #fbe6db;
      padding: 0px 20px;
      &:disabled {
        opacity: 0.5;
        pointer-events: none;
      }
      &:hover:not(:disabled) {
        opacity: 0.9;
      }
    }
  }
</style>
